package pl.un4giv3n.mightvsmagic.action.clan;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.entity.Clan;
import pl.un4giv3n.mightvsmagic.entity.ClanWar;

public class StartClanWarAction extends ClanAction{

	private static final long serialVersionUID = 1L;
	private String clanName;

	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		clan = user.getClan();
		Query query = entityManager.createNamedQuery("find.clan.by.name");
		query.setParameter("name", clanName);
		List<Clan> clans = query.getResultList();
		if(clan == null || clans == null || clans.isEmpty()){
			addActionError("Wybrany klan nie istnieje");
			entityManager.close();
			return ERROR;
		}
		Clan defendingClan = clans.get(0);
		if(defendingClan.getId().longValue() == clan.getId().longValue()){
			addActionError("Nie możesz zaatakować swojego klanu");
			entityManager.close();
			return ERROR;
		}
		ClanWar war = new ClanWar();
		war.setAttackerId(clan.getId());
		war.setAttackerName(clan.getName());
		war.setDefenderId(defendingClan.getId());
		war.setDefenderName(defendingClan.getName());
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		entityManager.persist(war);
		entityManager.flush();
		transaction.commit();
		return SUCCESS;
	}

	public String getClanName() {
		return clanName;
	}

	public void setClanName(String clanName) {
		this.clanName = clanName;
	}


}
